package io.gitee.thinkbungee.config;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 实现mongo的连接
 *
 * @author chenyichang
 * @date 2022/3/8
 */
@Component
@ConfigurationProperties(prefix = "mongodb")
public class MongoConfig {
    private String host;
    private int port;
    private String username;
    private String password;
    private String dataBase;
    private boolean auth;

    @Bean
    @Conditional(MongoCondition.class)
    private MongoClient mongoClient() {
        List<ServerAddress> addressList = new ArrayList<>();
        ServerAddress serverAddress = new ServerAddress(host, port);
        addressList.add(serverAddress);
        if (this.auth) {
            MongoCredential credential = MongoCredential.createCredential(username, dataBase, password.toCharArray());
            MongoClientOptions options = MongoClientOptions.builder().build();
            return new MongoClient(addressList, credential, options);
        }
        return new MongoClient(addressList);
    }


    @Bean
    @Conditional(MongoCondition.class)
    public MongoDatabase mongoDateBase() {
        return mongoClient().getDatabase(dataBase);
    }


    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDataBase() {
        return dataBase;
    }

    public void setDataBase(String dataBase) {
        this.dataBase = dataBase;
    }

    public boolean isAuth() {
        return auth;
    }

    public void setAuth(boolean auth) {
        this.auth = auth;
    }

}
